﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.PreservedEntities.CApPreservedObjectsEnabler
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using System.Collections.ObjectModel;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.PreservedEntities;

internal class CApPreservedObjectsEnabler : ITxCommandEnabler
{
  private bool m_preserved;

  public CApPreservedObjectsEnabler(bool preserved) => this.m_preserved = preserved;

  private bool CheckEnable()
  {
    bool flag1 = false;
    TxTypeFilter txTypeFilter = new TxTypeFilter();
    txTypeFilter.AddIncludedType(typeof (ITxDetailedRepresentation));
    TxObjectList filteredItems = TxApplication.ActiveSelection.GetFilteredItems((ITxTypeFilter) txTypeFilter);
    if (((Collection<ITxObject>) filteredItems).Count > 0 && ((Collection<ITxObject>) filteredItems).Count == TxApplication.ActiveSelection.Count)
      flag1 = true;
    if (flag1)
    {
      bool flag2 = false;
      foreach (ITxObject itxObject in (Collection<ITxObject>) filteredItems)
      {
        if (itxObject is ITxDetailedRepresentation detailedRepresentation && (this.m_preserved ? detailedRepresentation.CanPreserved() : detailedRepresentation.CanUnpreserved()))
          flag2 = true;
        ITxComponent parentComponent = this.GetParentComponent(itxObject);
        if (parentComponent == null || !parentComponent.IsOpenForModeling || TxEngineeringDataInternal.ObjectIsSectionCut((ITxObject) parentComponent))
        {
          flag1 = false;
          break;
        }
      }
      if (flag1)
        flag1 = flag2;
    }
    if (flag1 && ((Collection<ITxObject>) filteredItems).Count == 1)
    {
      if (((Collection<ITxObject>) filteredItems)[0] is ITxDetailedRepresentation detailedRepresentation1)
      {
        if (this.m_preserved)
        {
          if (!detailedRepresentation1.CanPreserved() || detailedRepresentation1.Preserved)
            flag1 = false;
        }
        else if (!detailedRepresentation1.CanUnpreserved() || !detailedRepresentation1.Preserved)
          flag1 = false;
      }
      else
        flag1 = false;
    }
    return flag1;
  }

  private ITxComponent GetParentComponent(ITxObject obj)
  {
    ITxObject collection = (ITxObject) obj.Collection;
    while (true)
    {
      switch (collection)
      {
        case null:
        case ITxComponent _:
          goto label_3;
        default:
          collection = (ITxObject) collection.Collection;
          continue;
      }
    }
label_3:
    return collection as ITxComponent;
  }

  public bool Enable => this.CheckEnable();
}
